<template>
  <div class="batch">
    <el-row type="flex">
      <InnerSidebar v-model="sidebarCollapsed">
        <template #header>
          <h2 class="inline-block">{{ $t("menu.M_10400008") }}</h2>
            <div class="flex items-center">
              <el-input
                v-model="key_word"
                :placeholder="$t('batch.batch_name')"
                size="mini"
                style="width: 200px; padding-right: 5px"
                maxlength="32"
                @blur="() => (key_word = key_word.trim())"
                @keyup.enter.native="handleSearch()"
              />
              <el-button type="primary" class="w-8" @click="handleSearch()">
                <svg-icon icon-class="Search"/>
              </el-button>
              <el-button
                class="w-8"
                type="primary"
                v-permission="{
                  permission: '10400008.MANAGE',
                  condition: {},
                }"
                @click="addBatchVisible = true"
              >
                <svg-icon icon-class="Plus"/>
              </el-button>
            </div>
        </template>
        <template #default>
          <ul class="text-sm list">
            <li
              class="item"
              v-for="(batch, index) in batchList"
              :key="batch.batchId"                            
              :class="{ active: activeId == batch.batchId }"
              @click="() => handleClick(index, batch, 'task')"
            >
              <span
                style="
                  width: 250px;
                  text-overflow: ellipsis;
                  overflow: hidden;
                  white-space: nowrap;
                "
                >{{ batch.name }}</span
              >
              <el-tooltip :content="batch.deviceCount + ''" placement="top">
                <div class="flex justify-end items-center flex-overflow">
                  <span class="text-secondary mr-3">{{
                    batch.deviceCount <= 9999 ? batch.deviceCount : "9999+"
                  }}</span>
                  <img src="../../../icons/group/terminal.png" width="24" />
                </div>
              </el-tooltip>
            </li>
          </ul>
        </template> 
      </InnerSidebar>
      <!-- <transition name="fade-transform" mode="out-in"> -->
        <router-view :key="key" :sidebar-collapsed="sidebarCollapsed"/>
      <!-- </transition> -->
    </el-row>

    <el-dialog
      v-model="addBatchVisible"
      :title="$t('batch.add_title')"
      width="450px"
      append-to-body
      @close="closeDialog('addform')"
    >
      <el-form
        @submit.prevent.native
        ref="addform"
        :model="form"
        :rules="rules"
        label-position="top"
      >
        <el-form-item :label="$t('batch.batch_name') + ':'" prop="name">
          <el-input
            v-model="form.name"
            maxlength="32"
            show-word-limit
            :placeholder="$t('common.msg_enterPlease')"
            autocomplete="off"
            @blur="() => (form.name = form.name.trim())"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button text @click="cancelAdd('addform')">{{
            $t("page.cancel")
          }}</el-button>
          <el-button
            type="primary"
            :loading="loading"
            @click="add('addform')"
            >{{ $t("page.confirm") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { queryBatchList, addBatch } from "@/api/batch";
import common from "@/utils/common";
import InnerSidebar from '@/components/InnerSidebar/index.vue'

export default {
  components: {
    InnerSidebar
  },
  data() {
    var validateInput = (rule, value, callback) => {
      if (!common.checkSpecificKey(value)) {
        callback(new Error(this.$t("common.page_tip_specialSymbol")));
      } else {
        callback();
      }
    };
    return {
      activeTab: "detail",
      key_word: "",
      index: -1,
      batchList: [],
      addBatchVisible: false,
      loading: false,
      form: {
        name: "",
      },
      rules: {
        name: [
          {
            required: true,
            message: this.$t("common.rule_input"),
            trigger: "blur",
          },
          { validator: validateInput, trigger: ["blur", "change"] },
        ],
      },
      sidebarCollapsed: false
    };
  },
  computed: {
    activeId() {
      return this.$route.params.id;
    },
    key() {
      return this.$route.path;
    },
  },
  mounted() {
    this.handleSearch();
    this.bindBusEvent();
  },
  methods: {
    handleClick(index, batch, activeName) {
      if (index) {
        this.index = index;
      }
      this.$router.push({
        path: `/tms/group/index/${batch.batchId}`,
        query: {
          name: batch.name,
          activeName: activeName,
          deviceCount: batch.deviceCount,
        },
      });
    },
    handleSearch(isAdd) {
      queryBatchList({ name: this.key_word })
        .then((res) => {
          console.log("fresh");
          this.batchList = res;
          if (isAdd) {
            this.handleClick(this.batchList[this.batchList.length - 1], "terminal");
          } else {
            // if (this.index >= 0) {
            //   this.handleClick(this.index, this.batchList[this.index], 'task')
            // }
          }
        })
        .catch(this.$confirmError);
    },
    cancelAdd(formName) {
      this.$nextTick(() => {
        this.addBatchVisible = false;
      });
    },
    add(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true;
          addBatch(this.form)
            .then((res) => {
              this.loading = false;
              this.addBatchVisible = false;
              this.$message.success(this.$t("common.msg_succeed"));
              this.$router.push({
                path: `/tms/group/index/${res.batchId}`,
                query: { name: res.name, activeName: "terminal", deviceCount: 0 },
              });
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        } else {
          console.log("error add!!");
          return false;
        }
      });
    },
    closeDialog(formName) {
      this.$refs[formName].resetFields();
    },
    bindBusEvent() {
      var that = this;
      this.$bus.on("freshTerminalCount", function (data) {
        console.log("freshTerminalCount");
        that.handleSearch();
      });
      this.$bus.on("freshBatch", function (data) {
        that.handleClick(null, data, "task");
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/mixin.scss";
@import "@/styles/variables.scss";

</style>

<style scoped>
.batch >>> .banner {
  background-image: url("../../../assets/images/banner/group-banner.png");
  height: 100px;
  background-size: cover;
  background-position: center;
  color: #e2e6ed;
}

.flex-overflow {
  flex: 0 0 120px;
}
</style>
